// test_api.js
const http = require('http');

// 首先登录获取token
const loginData = JSON.stringify({
  username: 'admin',
  password: '123456'
});

const loginOptions = {
  hostname: 'localhost',
  port: 9001,
  path: '/api/v1/auth/login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(loginData)
  }
};

const loginReq = http.request(loginOptions, (res) => {
  let loginResponse = '';
  
  res.on('data', (chunk) => {
    loginResponse += chunk;
  });
  
  res.on('end', () => {
    console.log('登录响应:');
    console.log(loginResponse);
    
    try {
      const loginResult = JSON.parse(loginResponse);
      if (loginResult.code === 0 && loginResult.data && loginResult.data.token) {
        const token = loginResult.data.token;
        console.log('获取到token:', token);
        
        // 使用token调用用户列表API
        const userOptions = {
          hostname: 'localhost',
          port: 9001,
          path: '/api/v1/system/users?page=1&limit=20&name=&email=&role=&status=',
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        };
        
        const userReq = http.request(userOptions, (res) => {
          let userResponse = '';
          
          res.on('data', (chunk) => {
            userResponse += chunk;
          });
          
          res.on('end', () => {
            console.log('\n用户列表响应:');
            console.log(userResponse);
            
            try {
              const userResult = JSON.parse(userResponse);
              console.log('\n用户列表数据:');
              console.log(JSON.stringify(userResult, null, 2));
            } catch (e) {
              console.error('解析用户列表响应失败:', e);
            }
          });
        });
        
        userReq.on('error', (e) => {
          console.error('调用用户列表API失败:', e);
        });
        
        userReq.end();
      } else {
        console.error('登录失败:', loginResponse);
      }
    } catch (e) {
      console.error('解析登录响应失败:', e);
    }
  });
});

loginReq.on('error', (e) => {
  console.error('登录请求失败:', e);
});

loginReq.write(loginData);
loginReq.end();